# -*- coding:utf-8 -*-
# @FileName  :operate_db.py
# @Time      :2020/10/22 15:30
# @Author    :zhoujirong

import cx_Oracle
import pymysql
import traceback
from common.log import Log
from common.config_parse import parse_ini

class MySQL:#操作mysql数据库
    def __init__(self,host,user,password,db,charset='utf8',autocommit=True,port=3306):
        port = int(port)
        Log.info('连接mysql数据库')
        self.conn = pymysql.connect(user=user,
                                    host=host,password=password,db=db,
                                    port=port,
                                    charset=charset,autocommit=autocommit)
        self.cursor = self.conn.cursor(pymysql.cursors.DictCursor)
        Log.info("开始连接mysql")

    def __del__(self):
        self.__close()

    def execute(self,sql):
        try:
            self.cursor.execute(sql)
        except Exception:
            Log.error('sql执行出错，sql语句是{}',sql)
            Log.error(traceback.format_exc())

    def fetchall(self,sql):
        self.execute(sql)
        return self.cursor.fetchall()

    def fetchone(self,sql):
        self.execute(sql)
        return self.cursor.fetchone()

    def table_exists(self,table_name):
        sql = "SELECT table_name FROM information_schema.TABLES WHERE table_name ='%s';"%table_name
        if self.fetchone(sql):
            return True

    def __close(self):
        self.cursor.close()
        self.conn.close()


class MyOracle:#操作oracle数据库
    def __init__(self,username,password,host,port,instance):
        try:
            Log.info('连接oracle数据库')
            self.conn = cx_Oracle.connect("%s/%s@%s:%s/%s" % (username,password,host,port,instance))
            self.cursor = self.conn.cursor()
        except Exception as e:
            Log.error("数据库连接出错了！", e)
    def execute(self,sql):
        try:
            self.cursor.execute(sql)
            self.conn.commit()
        except Exception as e:
            Log.error("sql语句%s出错了！"%sql, e)

    def fetchone(self,sql):
        try:
            self.cursor.execute(sql)
        except Exception as e:
            Log.error("sql语句%s出错了！"%sql, e)
        else:
            return self.cursor.fetchone()

    def fetchall(self, sql):
        try:
            self.cursor.execute(sql)
        except Exception as e:
            Log.error('sql语句有误！%s' % e)
        else:
            return self.cursor.fetchall()

    def table_exists(self, table_name):
        sql = "select count(*) from user_tables where table_name =upper('%s')" % table_name
        if self.fetchone(sql):
            return True

    def close(self):
        self.cursor.close()
        self.conn.close()


if __name__ == "__main__":
    oracle_data = parse_ini('oracle')
    print(oracle_data)
    a = MyOracle(**oracle_data).fetchall('select * from cpq_config')
    print(a)